package com.xmwzw.catpu;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author : wangzw
 * @date : 20-4-20下午3:16
 * @desc :
 */
public class DynamicProxyTest2 {

    @Test
    public void test() {

        RealSubject realSubject = new RealSubject();

        MyInvocationHandler handler = new MyInvocationHandler(realSubject);
        Subject subject= (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler);

        subject.register();
    }

    interface Subject {
        void register();

        void login();
    }

    class RealSubject implements Subject {

        @Override
        public void register() {
            System.out.println("real register");
        }

        @Override
        public void login() {
            System.out.println("real login");
        }
    }


    class MyInvocationHandler implements InvocationHandler{
        private Object realSubject ;

        public MyInvocationHandler(Object realSubject) {
            this.realSubject = realSubject;
        }

        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            System.out.println("执行前的准备操作");
            Object invoke = method.invoke(realSubject, objects);
            System.out.println();
            return invoke;
        }
    }
}
